package com.zsy.service.Impl;

import com.zsy.dao.ShoppingCartDao;
import com.zsy.pojo.ShoppingCart;
import com.zsy.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Override
    public ShoppingCart save(ShoppingCart shoppingCart) {
        ShoppingCart shoppingCartOne = shoppingCartDao.findUidAndDidOrSid(shoppingCart);
        if (shoppingCartOne == null) {
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartDao.save(shoppingCart);
            shoppingCartOne = shoppingCart;
        } else {
            shoppingCartOne.setNumber(shoppingCartOne.getNumber() + 1);
            shoppingCartDao.update(shoppingCartOne);
        }

        return shoppingCartOne;


    }

    @Override
    public List<ShoppingCart> list(Long userId) {

        return shoppingCartDao.list(userId);
    }

    @Override
    public void clean(Long userId) {
        shoppingCartDao.clean(userId);
    }

    @Override
    @Transactional
    public ShoppingCart reducedDishes(ShoppingCart shoppingCart) {
        shoppingCart = shoppingCartDao.findByDishIdOrSid(shoppingCart);
        int number = shoppingCart.getNumber() - 1;
        if (number == 0) {
            shoppingCartDao.delete(shoppingCart);
        }
        shoppingCart.setNumber(number);
        shoppingCartDao.reducedDishes(shoppingCart);
        return shoppingCart;
    }
}
